<?php
namespace app\api\controller;

use app\common\controller\Api;
use addons\litestore\model\Litestoreorder;
use app\admin\model\LitestoreServiceOrderType;
use app\admin\model\LitestoreServiceOrder;
use addons\third\model\Third;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use think\Db;
use think\Log;

class Order extends Api
{
	protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['buyvippay','callback_for_wxapp','callback_for_wxgzh'];

	public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new LitestoreServiceOrder;

    }
  

     /**
      * 升级VIP会员
      * @param service_order_type_id  VIP类型ID
      * @param user_id 用户ID
      */
    public function buyvippay()
    {
        //获取请求参数
        $servie_type_id = $this->request->post('service_order_type_id');//服务订单类型Id
        $user_id        = $this->request->post('user_id');              //用户ID

        //检查参数是否正确
        if(empty($servie_type_id))
        {
            $this->error(__('服务订单类型Id不能为空'));
        }
        if(empty($user_id))
        {
            $this->error(__('用户ID不能为空'));
        }
        //查询订单服务类型信息
        $litestoreServiceOrderType = new LitestoreServiceOrderType();
        $serviceTypelist = $litestoreServiceOrderType->where("id = ".$servie_type_id)->limit(1)->select();
        if(empty($serviceTypelist))
        {
            $this->error(__('服务订单类型在数据库中未找到记录'));
        }
        $serviceType = $serviceTypelist[0];

        //创建订单
        $this->model->save([
            'user_id' => $user_id,
            'nickname'=>$this->findUserName($user_id),
            'order_no' => $this->orderNo(),
            'total_price' => $serviceType['price'],//商品金额
            'pay_price' => $serviceType['price'],//订单总支付金额
            'order_type_id' =>$serviceType['id'],
            'pay_status' =>'10',//支付状态:10=未支付,20=已支付'
            'order_status'=>'10',//'订单状态:10=进行中,20=取消,30=已完成'
            'createtime'=>time(),//创建时间
            'updatetime'=>time(),//更新时间
        ]);

        //微信接口初始化
        $this->init_wx_pay_for_wxapp();

        //微信预支付
        $this->make_wx_pay('wxapp',$user_id);
        //$this->updateBusiness( $this->model['order_no'],'111111', true);

       return $this->success('',['order' =>  $this->model]);
    }
    /**
     * 微信接口初始化
     */
    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('litestore');
        $options = [
                    'app_id'   => $config['AppID'],
                    'secret'   => $config['AppSecret'],
                    'payment' => [
                        'merchant_id'        =>  $config['MCHID'],
                        'key'                =>  $config['APIKEY'],
                        'notify_url'         =>  \think\Request::instance()->domain().'/api/order/callback_for_wxapp', 
                    ],

                  ];
                  Log::info('********************************init_wx_pay_for_wxapp $options ');                  
                  Log::info($options);                  
        $this->wxapp = new WXPAY_APP($options);
    }
    /**
     * 微信预支付
     */
    private function make_wx_pay($platform,$user_id){
    	$third = Third::where(['user_id' => $user_id, 'platform' => $platform])->find();

        $payment = $this->wxapp->payment;

        $attributes = [
		    'trade_type'       => 'JSAPI',
		    'body'             => $this->model['order_no'],
		    'detail'           => 'OrderID:'.$this->model['id'],
		    'out_trade_no'     => $this->model['order_no'],
		    'total_fee'        => $this->model['pay_price'] * 100, // 单位：分
          //  'total_fee'        => 1, // 单位：分
		    'openid'           => $third['openid'],
		];
        $order = new WXPAY_ORDER($attributes);
        $result = $payment->prepare($order);

        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
		    $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
			return $this->success('预支付成功',$config);
		}
		return $this->error('微信支付调用失败',$result);
    }

    
    public function callback_for_wxapp(){
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->payment->handleNotify(function($notify, $successful){
            return $this->updateBusiness($notify->out_trade_no,$notify->transaction_id,$successful);
        });
        $response->send();
    }
    /**
     * 更新订单信息的状态
     * 
     */
    public function updateBusiness($out_trade_no,$transaction_id, $successful){
 
 
        $orderList = Db::query("select * from fa_litestore_service_order where order_no=:order_no limit 1 ",['order_no'=>$out_trade_no]);
        if(empty($orderList))
        {
          return true;// 如果订单不存在 // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        $order = $orderList[0];

        if ($successful) {
            Db::startTrans();
             // 更新订单状态
             Db::name('litestore_service_order')->where(['order_no'=>$out_trade_no])->update([
                'pay_status' => '20',
                'order_status' => '30',
                'pay_time' => time(),
                'transaction_id' => $transaction_id,
            ]);

            //判断缴费类型
            $service_order_type_id =$order['order_type_id'];
            
            $level ='1';//默认为免费用户
            if($service_order_type_id=='1')
            {
                $level='2' ;//普通会员
            }
            else if($service_order_type_id=='2')
            {
                $level='3' ;//明星企业会员
            }
            
            $now = date('Y-m-d',time());  
            $oneyear =  date("Y-m-d",strtotime("-1days",strtotime("+1years",strtotime(date('Y-m-d H:i:s',time())))));

            // 更新用户的类型状态
            Db::name('user')->where(['id'=> $order['user_id']])->update([
                'level' => $level,
                'updatetime' => time(),
                'effect_start_time'=> $now,
                'effect_end_time'=> $oneyear,
            ]);
            Db::commit();
        }
        return true; // 返回处理完成
    }

    protected function findUserName($user_id)
    {
        return Db::table('fa_user')->where('id', $user_id)->select()[0]['nickname'];
    }
    protected function orderNo()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

}
